﻿using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using UAParser;

namespace Vin.Tool.Core.NetCategory;

public class HttpContextTool
{
    /// <summary>
    /// 判断是否IP
    /// </summary>
    public static bool IsIp(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    /// <summary>
    /// 获取Form表单数据
    /// </summary>
    /// <param name="form"></param>
    /// <returns></returns>
    public static string FormString(IFormCollection form)
    {
        return string.Join("&", form.Select(m => $"{m.Key}={m.Value}"));
    }

    public static Dictionary<string, string> FormDictionary(IFormCollection form)
    {
        return form.ToDictionary(m => m.Key, m => m.Value.ToString());
    }

    public static string ToCurl(HttpContext context)
    {
        var curlItemKey = "Curl";
        var curl = context.GetItems<string>(curlItemKey);
        if (!string.IsNullOrEmpty(curl)) return curl;

        StringBuilder sb = new StringBuilder();
        sb.Append("curl ");
        sb.Append($"-X {context.Request.Method} ");
        sb.Append($"\"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}\" ");

        foreach (var query in context.Request.Query)
        {
            sb.Append($"-d '{query.Key}={query.Value}' ");
        }
        
        foreach (var header in context.Request.Headers)
        {
            sb.Append($"-H \"{header.Key}:{string.Join(",", header.Value.ToString())}\" \n");
        }

        if (context.Request.Method == "POST" && !context.Request.HasFormContentType)
        {
            sb.Append($"-d '{context.ReadToString().Result}' ");
        }

        if (context.Request.Method == "POST" && context.Request.HasFormContentType)
        {
            sb.Append($"-d '{FormString(context.Request.Form)}' ");
        }

        curl = sb.ToString();
        context.SetItems(curlItemKey, curl);

        return curl;
    }

    /// <summary>
    /// 获取浏览器信息
    /// </summary>
    public static ClientInfo ParserUserAgent(string str)
    {
        return Parser.GetDefault().Parse(str);
    }
}